package com.songtech.elefence.controller;

import com.github.pagehelper.PageInfo;
import com.songtech.base.common.BaseConstant;
import com.songtech.base.common.JsonResult;
import com.songtech.elefence.service.EleFenceService;
import com.songtech.login.model.SysPosUser;
import com.songtech.server.Jedis.JedisBaseDao;
import com.songtech.server.constant.KeysConstant;
import com.songtech.web.entry.SysPosElefence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Create by WH on 2018/4/11 11:11
 *
 * @Description :
 */

@Controller
@RequestMapping("/eleFence")
public class EleFenceController {

    private Logger logger = LoggerFactory.getLogger(EleFenceController.class);

    /**
     * redis操作对象
     */
    @Autowired
    private JedisBaseDao<Serializable> jedisBaseDao;

    @Autowired
    private EleFenceService elefenceService;

    /**
     * 新增--电子围栏
     * @param fence  elefenceName '电子围栏名称',
                     centerLongitude '中心点经度',
                     centerLatitude '中心点纬度',
                     radius '半径（米）',
     * @return
     */
    @RequestMapping("/addFence")
    @ResponseBody
    public JsonResult saveFence(@RequestBody SysPosElefence fence, HttpServletRequest request){
        int count = 0;
        fence = setFence(fence, request, 1);  //获取set后的fence
        //验证，暂时写在这里，后面提出来。
        SysPosElefence fenceForValid = new SysPosElefence();
        setFence(fenceForValid, request, 3);  //获取set后的fence,验证重名
        fenceForValid.setElefenceName(fence.getElefenceName().trim());
        if("".equals(fenceForValid.getElefenceName())){
            return new JsonResult(0, BaseConstant.FAIL_CODE, "围栏名称不能为空");
        }
        if(fence.getElefenceName().length() > 10){
            return new JsonResult(0, BaseConstant.FAIL_CODE, "围栏名称长度不能超过10个字");
        }
        if(isSpecialChar(fence.getElefenceName())){
            return new JsonResult(0, BaseConstant.FAIL_CODE, "不能输入特殊符号");
        }
        try {
            PageInfo<SysPosElefence> fenceList = elefenceService.selectFenceList(fenceForValid); //验证重名
            if(fenceList.getTotal() > 0){return new JsonResult(count, BaseConstant.FAIL_CODE, "围栏名称已存在");}
            count = elefenceService.insertFence(fence); //查询电子围栏
            jedisBaseDao.put(KeysConstant.ELE_FENCE + "_" + fence.getImei(), fence); //新增成功后，添加到缓存
        } catch (SQLException e) {
            logger.error("添加围栏异常信息:"+e.getMessage(),e);
            return new JsonResult(count, BaseConstant.FAIL_CODE, BaseConstant.FAIL);
        }
        return new JsonResult(count, BaseConstant.SUCCESS_CODE, BaseConstant.SUCCESS);
    }

    /**
     * 查询--电子围栏列表
     * @param
     * @return
     */
    @RequestMapping(value = "/selectFence",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult selectFenceList(HttpServletRequest request,Integer pageNum,Integer pageSize){
        SysPosElefence fence = new SysPosElefence();
        fence = setFence(fence, request, 3);
        Map<Object, Object> map = new HashMap<>();
        try {
            PageInfo<SysPosElefence> fenceList = elefenceService.selectFenceList(fence, pageSize, pageNum);
            map.put("data",fenceList.getList());//查询的列表数据
            map.put("total",fenceList.getTotal());//数据总数
        } catch (SQLException e) {
            logger.error("查询围栏列表异常信息:"+e.getMessage(),e);
            return new JsonResult(map, BaseConstant.FAIL_CODE, BaseConstant.FAIL);
        }
        return new JsonResult(map, BaseConstant.SUCCESS_CODE, BaseConstant.SUCCESS);
    }

    /**
     * 删除--电子围栏
     * @param elefenceId    elefenceId '电子围栏id'
     * @return
     */
    @RequestMapping(value = "/deletFence",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult deletFence(Integer elefenceId,HttpServletRequest request){
        int count = 0;
        try {
            count = elefenceService.deleteFence(elefenceId);
            SysPosUser user = (SysPosUser)request.getSession().getAttribute("loginUser"); //获取用户信息
            jedisBaseDao.delete(KeysConstant.ELE_FENCE + "_" + user.getImei()); //删除成功后，销毁缓存
        } catch (SQLException e) {
            logger.error("删除围栏异常信息:"+e.getMessage(),e);
            return new JsonResult(count, BaseConstant.FAIL_CODE, BaseConstant.FAIL);
        }
        return new JsonResult(count, BaseConstant.SUCCESS_CODE, BaseConstant.SUCCESS);
    }

    /**
     * 更新--电子围栏 (只更新 不为null 的字段)
     * @param fence  elefenceId '电子围栏id'，
     *               elefenceName '电子围栏名称',
     *               centerLongitude '中心点经度',
     *               centerLatitude '中心点纬度',
     *               radius '半径（米）'
     * @return
     */
    @RequestMapping("/updateFence")
    @ResponseBody
    public JsonResult updateFence(@RequestBody SysPosElefence fence, HttpServletRequest request){
        int count = 0;
        fence = setFence(fence, request, 2);
        //验证，暂时写在这里，后面提出来。
        SysPosElefence fenceForValid = new SysPosElefence();
        setFence(fenceForValid, request, 3);  //获取set后的fence,验证重名
        fenceForValid.setElefenceName(fence.getElefenceName().trim());
        if("".equals(fenceForValid.getElefenceName())){
            return new JsonResult(0, BaseConstant.FAIL_CODE, "围栏名称不能为空");
        }
        if(fenceForValid.getElefenceName().length() > 10){
            return new JsonResult(0, BaseConstant.FAIL_CODE, "围栏名称长度不能超过10个字");
        }
        if(isSpecialChar(fenceForValid.getElefenceName())){
            return new JsonResult(0, BaseConstant.FAIL_CODE, "不能输入特殊符号");
        }
        if(fence.getElefenceId() != null){
            try {
                PageInfo<SysPosElefence> fenceList = elefenceService.selectFenceList(fenceForValid); //验证重名
                if(fenceList.getTotal() > 0){
                    if(!fence.getElefenceName().equals(fenceList.getList().get(0).getElefenceName())){
                        return new JsonResult(count, BaseConstant.FAIL_CODE, "围栏名称已存在");
                    }
                }
                count = elefenceService.updateFence(fence);
                jedisBaseDao.put(KeysConstant.ELE_FENCE + "_" + fence.getImei(), fence); //更新成功后，添加到缓存
            } catch (SQLException e) {
                logger.error("更新围栏异常信息:"+e.getMessage(),e);
                return new JsonResult(count, BaseConstant.FAIL_CODE, BaseConstant.FAIL);
            }
        }
        return new JsonResult(count, BaseConstant.SUCCESS_CODE, BaseConstant.SUCCESS);
    }

    /**
     * 包装实体 -- 新增/修改/查询
     * @param fence 已有的实体
     * @param request
     * @param type 包装类型（1.新增 2.修改 3.查询）
     * @return
     */
    public SysPosElefence setFence(SysPosElefence fence,  HttpServletRequest request, int type){
        SysPosUser user = (SysPosUser)request.getSession().getAttribute("loginUser"); //获取用户信息
        //新增时set值
        if(type == 1){
            fence.setImei(user.getImei()); //获取session--身份标识
            fence.setCreateUser(user.getPosUserName()); //用户名
            fence.setCreateTime(new Date());
            fence.setStatus(1);
        }
        //修改时set值
        if(type == 2){
            fence.setUpdateUser(user.getPosUserName());
            fence.setUpdateTime(new Date());
        }
        //查询时set值
        if(type == 3){
            fence.setImei(user.getImei()); //获取session--身份标识
            fence.setStatus(1); //可用的
        }
        return fence;
    }

    /**
     * 数据验证（暂时没用它）
     * @param fence
     * @param request
     * @return
     */
    public JsonResult validFence(SysPosElefence fence, HttpServletRequest request){
        if("".equals(fence.getElefenceName().trim())){
            return new JsonResult(0, BaseConstant.FAIL_CODE, "围栏名称不能为空");
        }
        if(fence.getElefenceName().trim().length() > 10){
            return new JsonResult(0, BaseConstant.FAIL_CODE, "围栏名称长度不能超过10个字");
        }
        fence = setFence(fence,request,3);
        try {
            PageInfo<SysPosElefence> fenceList = elefenceService.selectFenceList(fence);
            if(fenceList.getTotal() > 0){return new JsonResult(0, BaseConstant.FAIL_CODE, "围栏名称已存在");}
        } catch (SQLException e) {
            logger.error("围栏数据验证异常信息:"+e.getMessage(),e);
            return new JsonResult(0, BaseConstant.FAIL_CODE, BaseConstant.FAIL);
        }
        return new JsonResult(0, BaseConstant.SUCCESS_CODE, BaseConstant.SUCCESS);
    }

    /**
     * 判断是否含有特殊字符
     * @param str
     * @return true为包含，false为不包含
     */
    public static boolean isSpecialChar(String str) {
        String regEx = "[_`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }
}
